﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HanGu.Services.Interface;
using HanGu.Entity;
using System.Transactions;
using HanGu.Common;
using System.Data.Objects.SqlClient;
//using LinqKit;
using System.Linq.Expressions;

namespace HanGu.Services
{
    public class MemberInfoService : BaseService, IMemberInfo
    {

        public List<MemberInfo> GetAll()
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.MemberInfo.OrderByDescending(c => c.UpdateTime).ToList();
            }
        }
        public List<MemberInfo> GetAllByAssignedIn(int managerID)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var AssignedIns = obj.MemberAssigned.Where(c => c.ManagerID == managerID).Select(c => c.MemberID).ToList<int>();
                return obj.MemberInfo.Where(c => AssignedIns.Contains(c.ID)).OrderByDescending(c => c.UpdateTime).ToList();
            }
        }
        public List<MemberInfo> GetAll(UniversallySearchParam searchparma)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var query = obj.MemberInfo.Where(c => 1 == 1);

                if (!string.IsNullOrEmpty(searchparma.Ttile))
                {
                    query = query.Where(c => c.UserName.IndexOf(searchparma.Ttile) >= 0);
                }
                if (!string.IsNullOrEmpty(searchparma.Lectcher))
                {
                    query = query.Where(c => c.Grade.IndexOf(searchparma.Lectcher) >= 0);
                }
                if (!string.IsNullOrEmpty(searchparma.Suitabler))
                {
                    query = query.Where(c => c.UserName.IndexOf(searchparma.Suitabler) >= 0);
                }
                if (!string.IsNullOrEmpty(searchparma.Degree))
                {
                    query = query.Where(c => c.Degree == searchparma.Degree);
                }
                if (searchparma.StarDateTime.HasValue)
                {
                    query = query.Where(c => c.UpdateTime >= searchparma.StarDateTime);
                }
                if (searchparma.EndDateTime.HasValue)
                {
                    query = query.Where(c => c.UpdateTime <= searchparma.EndDateTime);
                }
                if (searchparma.IsBacklist != null && searchparma.IsBacklist.HasValue && searchparma.IsBacklist.Value)//显示黑名单
                {
                    //query = query.Where(c => c.IsBacklist == true);

                }
                else
                {
                    query = query.Where(c => c.IsBacklist == false);
                }

                if (!string.IsNullOrEmpty(searchparma.Sex))
                {
                    query = query.Where(c => c.Sex == searchparma.Sex);
                }
                if (!string.IsNullOrEmpty(searchparma.Tel)) { query = query.Where(c => c.Tel.IndexOf(searchparma.Tel) >= 0); }
                if (!string.IsNullOrEmpty(searchparma.NativePlace)) { query = query.Where(c => c.NativePlace == searchparma.NativePlace); }
                if (!string.IsNullOrEmpty(searchparma.IsMarry)) { query = query.Where(c => c.IsMarry == searchparma.IsMarry); }
                if (searchparma.HasChildren.HasValue && searchparma.HasChildren.Value) { query = query.Where(c => c.IsChildren == true); }
                if (!string.IsNullOrEmpty(searchparma.Provice)) { query = query.Where(c => c.Provice == searchparma.Provice); }
                if (!string.IsNullOrEmpty(searchparma.City)) { query = query.Where(c => c.City == searchparma.City); }
                if (!string.IsNullOrEmpty(searchparma.Oganization)) { query = query.Where(c => c.Oganization == searchparma.Oganization); }


                if (searchparma.ChargeRandS.HasValue) { query = query.Where(c => c.Charge >= searchparma.ChargeRandS); }
                if (searchparma.ChargeRandE.HasValue) { query = query.Where(c => c.Charge <= searchparma.ChargeRandE); }
                if (searchparma.ContractRandS.HasValue) { query = query.Where(c => c.ContractTotal >= searchparma.ContractRandS); }
                if (searchparma.ContractRandE.HasValue) { query = query.Where(c => c.ContractTotal <= searchparma.ContractRandE); }
                if (searchparma.ContractNumRandS.HasValue) { query = query.Where(c => c.ContractNum >= searchparma.ContractNumRandS); }
                if (searchparma.ContractNumRandE.HasValue) { query = query.Where(c => c.ContractNum <= searchparma.ContractNumRandE); }
                if (!string.IsNullOrEmpty(searchparma.ImportantLevel)) { query = query.Where(c => c.ImportantLevel == searchparma.ImportantLevel); }
                if (searchparma.AssignedIn.HasValue) { query = query.Where(c => c.MemberAssigneds.Where(m => m.MemberID == searchparma.AssignedIn.Value) != null); }

                if (searchparma.IsPage.HasValue && !searchparma.IsPage.Value) { searchparma.Pagination.PageSize = Int32.MaxValue; searchparma.Pagination.IsPaging = false; }
                if (searchparma.SubAssignedIn != null && searchparma.SubAssignedIn.Count > 0)
                {
                    var AssignedIns = obj.MemberAssigned.Where(c => searchparma.SubAssignedIn.Contains(c.ManagerID)).Select(c => c.MemberID).ToList<int>();
                    query = query.Where(c => AssignedIns.Contains(c.ID));
                }
                if (!string.IsNullOrEmpty(searchparma.Groups))
                {
                    var Groups = searchparma.Groups.Split(',').Select(c => int.Parse(c)).ToList<int>();
                    var memberGroups = obj.VMemberGrouped.Where(c => Groups.Contains(c.GroupID));
                    var joinedGrops = new List<int>();
                    if (memberGroups != null && memberGroups.Count() > 0)
                    {
                        joinedGrops = memberGroups.Select(c => c.MemberID).ToList<int>();
                    }
                    query = query.Where(c => joinedGrops.Contains(c.ID));
                }
                
                if (!string.IsNullOrEmpty(searchparma.Trade))
                {
                    //var tradePredicate = PredicateExtensions.False<MemberInfo>();
                    //var tradeArray = searchparma.Trade.Split(',');
                    //foreach (var item in tradeArray)
                    //{
                    //    tradePredicate = tradePredicate.Or(c => c.Trade.IndexOf(item) >= 0);
                    //}
                    //query = query.AsExpandable().Where(tradePredicate);
                    
                    var tradeArray = searchparma.Trade.Split(',');
                    var tradePredicate = base.GenerateOrElseConditionWithArray<MemberInfo>("Trade", "IndexOf", tradeArray);
                    query = query.Where(tradePredicate);
                    
                   
                  
                }
                if (!string.IsNullOrEmpty(searchparma.Position))
                {
                    //var positionPredicate = PredicateExtensions.False<MemberInfo>();
                    var PositionArray = searchparma.Position.Split(',');
                    //foreach (var item in PositionArray)
                    //{
                    //    positionPredicate = positionPredicate.Or(c => c.Position.IndexOf(item) >= 0);
                    //}
                    //query = query.AsExpandable().Where(positionPredicate);
                    var positionPredicate = base.GenerateOrElseConditionWithArray<MemberInfo>("Position", "IndexOf", PositionArray);
                    query = query.Where(positionPredicate);
                }
                if (!string.IsNullOrEmpty(searchparma.Job))
                {
                    //var JobPredicate = PredicateExtensions.False<MemberInfo>();
                    var JobArray = searchparma.Job.Split(',');
                    //foreach (var item in JobArray)
                    //{
                    //    JobPredicate = JobPredicate.Or(c => c.Job.IndexOf(item) >= 0);
                    //}
                    //query = query.AsExpandable().Where(JobPredicate);
                    var JobPredicate = base.GenerateOrElseConditionWithArray<MemberInfo>("Job", "IndexOf", JobArray);
                    query = query.Where(JobPredicate);
                }
                if (!string.IsNullOrEmpty(searchparma.Interest))
                {
                    //var InterestPredicate = PredicateExtensions.False<MemberInfo>();
                    var InterestArray = searchparma.Interest.Split(',');
                    //foreach (var item in InterestArray)
                    //{
                    //    InterestPredicate = InterestPredicate.Or(c => c.Interest.IndexOf(item) >= 0);
                    //}
                    //query = query.AsExpandable().Where(InterestPredicate);
                    var InterestPredicate = base.GenerateOrElseConditionWithArray<MemberInfo>("Interest", "IndexOf", InterestArray);
                    query = query.Where(InterestPredicate);
                }

                query = base.Paging<MemberInfo, DateTime?>(c => c.UpdateTime, query, searchparma.Pagination);

                foreach (var item in query)
                {
                    item.MemberAssignedManagers = obj.vwMemberAssigned.Where(c => c.MemberID == item.ID).ToList();
                    item.MemberAssignedManagers = item.MemberAssignedManagers ?? new List<vwMemberAssigned>();
                }
                return query.ToList();
            }
        }
        public List<MemberInfo> GetSelectedByGroup(string groupid)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                string sql = "select * from memberinfo where id in(select  distinct memberid from VMemberGrouped where groupid in ({0}))";
                var query = obj.ExecuteStoreQuery<MemberInfo>(string.Format(sql, groupid));

                return query.ToList();
            }
        }
        public List<string> GetMemberName(string key = null)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var query = obj.MemberInfo.Where(c => 1 == 1);
                if (!string.IsNullOrEmpty(key))
                {
                    query = query.Where(c => c.UserName.IndexOf(key) >= 0 || c.UserName.IndexOf(key) >= 0);
                }
                return query.Select(c => c.RealName + "[" + SqlFunctions.StringConvert((double)c.ID).Trim() + "]").GroupBy(c => c).Select(c => c.Key).ToList();
            }
        }
        public List<string> GetOganization()
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.MemberInfo.GroupBy(c => c.Oganization).Select(c => c.Key).ToList();
            }
        }
        public List<MemberInfo> GetSelectedByIDs(string memberIDs)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                string sql = "select * from memberinfo where id in({0})";
                var query = obj.ExecuteStoreQuery<MemberInfo>(string.Format(sql, memberIDs));

                return query.ToList();
            }
        }
        public MemberInfo GetByID(int id)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var model = obj.MemberInfo.Where(c => c.ID == id).FirstOrDefault();
                if (model != null)
                {
                    model.MemberAssigneds = obj.MemberAssigned.Where(c => c.MemberID == id).ToList();
                    model.MemberAssigneds = model.MemberAssigneds ?? new List<MemberAssigned>();
                    model.MemberAssignedHis = obj.vwMemberAssignedHis.Where(c => c.MemberID == id).OrderByDescending(c => c.CreateDate).ToList();
                    model.MemberAssignedHis = model.MemberAssignedHis ?? new List<vwMemberAssignedHis>();
                }
                return model;
            }
        }
        public bool IsUserExits(string user)
        {
            bool isExits = false;
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var userModel = obj.MemberInfo.Where(c => c.UserName == user).FirstOrDefault();
                isExits = userModel != null;
            }
            return isExits;
        }
        public bool IsLogin(string user, string pwd)
        {
            bool tag = false;
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                tag = obj.MemberInfo.Where(c => c.UserName == user && c.Pwd == pwd).Count() > 0;
            }
            return tag;
        }

        public MemberInfo GetByUser(string user)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var model = obj.MemberInfo.Where(c => c.UserName == user).FirstOrDefault();
                if (model != null)
                {
                    model.MemberAssigneds = obj.MemberAssigned.Where(c => c.MemberID == model.ID).ToList();
                    model.MemberAssigneds = model.MemberAssigneds ?? new List<MemberAssigned>();
                    model.MemberAssignedHis = obj.vwMemberAssignedHis.Where(c => c.MemberID == model.ID).ToList();
                    model.MemberAssignedHis = model.MemberAssignedHis ?? new List<vwMemberAssignedHis>();

                }
                return model;
            }
        }
        public int IsResetPwd(string user, string email)
        {
            int tag = 0;
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var model = obj.MemberInfo.Where(c => c.UserName == user && c.Email == email.Trim()).FirstOrDefault();
                if (model != null)
                {
                    try
                    {
                        model.Pwd = Helper.MD5(Helper.DEFAULTPWD);
                        tag = Update(model) == true ? 0 : 2;

                    }
                    catch (Exception e)
                    {
                        base.ExceptionHand(e);
                        tag = -1;
                    }
                }
                else
                {
                    tag = 1;
                }

            }
            return tag;
        }
        public bool Add(MemberInfo model, List<MemberChildren> sMemberChildren = null, List<MemberContract> sMemberContract = null, List<vwMemberContact> memberContact = null)
        {
            try
            {
                //using (TransactionScope scope = new TransactionScope())
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        //this.Add<MemberInfo>(model);
                        obj.MemberInfo.AddObject(model);
                        obj.SaveChanges();

                        //保存所属
                        if (!string.IsNullOrEmpty(model.SelectedMemberAssigneds))
                        {
                            string sql = @"delete from MemberAssigned where MemberID={0};";
                            obj.ExecuteStoreCommand(string.Format(sql, model.ID));
                            foreach (var item in model.SelectedMemberAssigneds.Split(','))
                            {
                                int managerid = 0;
                                if (int.TryParse(item, out managerid))
                                {
                                    var memberAssigned = new MemberAssigned() { MemberID = model.ID, ManagerID = managerid };
                                    obj.MemberAssigned.AddObject(memberAssigned);
                                    var memberAssignedhis = new MemberAssignedHis() { MemberID = model.ID, ManagerID = managerid, CreateDate = DateTime.Now };
                                    obj.MemberAssignedHis.AddObject(memberAssignedhis);
                                }
                            }
                            obj.SaveChanges();
                        }

                        //保存群
                        string sql2 = @"delete from MemberGroup where MemberID={0};";
                        obj.ExecuteStoreCommand(string.Format(sql2, model.ID));
                        if (!string.IsNullOrEmpty(model.GroupID))
                        {

                            foreach (var item in model.GroupID.Split(','))
                            {
                                if (!string.IsNullOrEmpty(item))
                                {
                                    int groupid = 0;
                                    if (int.TryParse(item, out groupid))
                                    {
                                        var memberGroup = new MemberGroup() { MemberID = model.ID, GroupID = groupid };
                                        obj.MemberGroup.AddObject(memberGroup);
                                    }
                                }
                            }
                            obj.SaveChanges();
                        }
                        bool isCC = false;
                        //子女信息
                        if (sMemberChildren != null && sMemberChildren.Count > 0)
                        {
                            foreach (var item in sMemberChildren)
                            {
                                item.ID = 0;
                                item.ParentID = model.ID;
                                obj.MemberChildren.AddObject(item);
                                isCC = true;
                            }
                        }
                        //合同信息
                        if (sMemberContract != null && sMemberContract.Count > 0)
                        {
                            foreach (var item in sMemberContract)
                            {
                                item.ID = 0;
                                item.ParentID = model.ID;
                                obj.MemberContract.AddObject(item);
                                isCC = true;
                            }
                        }
                        //联系记录
                        if (memberContact != null && memberContact.Count > 0)
                        {
                            foreach (var item in memberContact)
                            {
                                item.ID = 0;
                                item.MemberID = model.ID;
                                obj.MemberContact.AddObject(TransferToContact(item));
                                isCC = true;
                            }
                        }
                        if (isCC) obj.SaveChanges();
                    }
                    //scope.Complete();
                    return true;
                }

            }
            catch { return false; }
        }

        public bool Update(MemberInfo model, List<MemberChildren> sMemberChildren = null, List<MemberContract> sMemberContract = null, List<vwMemberContact> memberContact = null)
        {
            try
            {


                //using (TransactionScope scope = new TransactionScope())
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        this.Update<MemberInfo>(model);
                        //保存所属
                        if (!string.IsNullOrEmpty(model.SelectedMemberAssigneds))
                        {
                            //base.Delete<MemberAssigned>(c => c.MemberID == model.ID);
                            string sql = @"delete from MemberAssigned where MemberID={0};";
                            obj.ExecuteStoreCommand(string.Format(sql, model.ID));
                            var newSelectedMemberAssigneds = model.SelectedMemberAssigneds.Split(',');
                            var oldSelectedMemberAssigneds = model.OldParents.Split(',');
                            foreach (var item in newSelectedMemberAssigneds)
                            {
                                int managerid = 0;
                                if (int.TryParse(item, out managerid))
                                {
                                    var memberAssigned = new MemberAssigned() { MemberID = model.ID, ManagerID = managerid };
                                    obj.MemberAssigned.AddObject(memberAssigned);
                                    if (!oldSelectedMemberAssigneds.Contains(item))
                                    {
                                        var memberAssignedhis = new MemberAssignedHis() { MemberID = model.ID, ManagerID = managerid, CreateDate = DateTime.Now };
                                        obj.MemberAssignedHis.AddObject(memberAssignedhis);
                                    }
                                }
                            }
                            obj.SaveChanges();
                        }
                        //保存群
                        //base.Delete<MemberGroup>(c => c.MemberID == model.ID);
                        string sql2 = @"delete from MemberGroup where MemberID={0};";
                        obj.ExecuteStoreCommand(string.Format(sql2, model.ID));
                        if (!string.IsNullOrEmpty(model.GroupID))
                        {

                            foreach (var item in model.GroupID.Split(','))
                            {
                                if (!string.IsNullOrEmpty(item))
                                {
                                    int groupid = 0;
                                    if (int.TryParse(item, out groupid))
                                    {
                                        var memberGroup = new MemberGroup() { MemberID = model.ID, GroupID = groupid };
                                        obj.MemberGroup.AddObject(memberGroup);
                                    }
                                }
                            }
                            obj.SaveChanges();
                        }
                        bool isCC = false;
                        //子女信息
                        if (sMemberChildren != null && sMemberChildren.Count > 0)
                        {
                            foreach (var item in sMemberChildren)
                            {
                                item.ID = item.ID < 0 ? 0 : item.ID;
                                item.ParentID = model.ID;
                                if (item.ID == 0)
                                {
                                    obj.MemberChildren.AddObject(item);
                                }
                                else
                                {
                                    base.Update<MemberChildren>(item);
                                }
                                isCC = true;
                            }
                        }
                        //合同信息
                        if (sMemberContract != null && sMemberContract.Count > 0)
                        {
                            foreach (var item in sMemberContract)
                            {
                                item.ID = item.ID < 0 ? 0 : item.ID;
                                item.ParentID = model.ID;
                                if (item.ID == 0)
                                {
                                    obj.MemberContract.AddObject(item);
                                }
                                else
                                {
                                    base.Update<MemberContract>(item);
                                }
                                isCC = true;
                            }
                        }
                        //联系记录
                        if (memberContact != null && memberContact.Count > 0)
                        {
                            foreach (var item in memberContact)
                            {
                                item.ID = item.ID < 0 ? 0 : item.ID;
                                item.MemberID = model.ID;
                                if (item.ID == 0)
                                {
                                    obj.MemberContact.AddObject(TransferToContact(item));
                                }
                                else
                                {
                                    base.Update<MemberContact>(TransferToContact(item));
                                }
                                isCC = true;
                            }
                        }
                        if (isCC) obj.SaveChanges();
                    }
                    //scope.Complete();
                    return true;
                }


            }
            catch { return false; }
        }

        public bool Delete(int id)
        {
            try
            {

                //using (var trans = obj.Connection.BeginTransaction())
                //{
                //    this.Delete<MemberInfo>(c => c.ID == id);
                //    trans.Commit();
                //}
                using (TransactionScope scope = new TransactionScope())
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        //this.Delete<MemberInfo>(c => c.ID == id);
                        //this.Delete<ChangeChargeRecorde>(c => c.VIPID == id);
                        //this.Delete<ChangeGradeRecorde>(c => c.VIPID == id);
                        //this.Delete<ChargeRecorde>(c => c.VIPID == id);
                        //this.Delete<Message>(c => c.MemberID == id);
                        string sql = @"delete from MemberInfo where id={0};
                                        delete from ChangeChargeRecorde where VIPID={0};
                                        delete from ChangeGradeRecorde where VIPID={0};
                                        delete from ChargeRecorde where VIPID={0};
                                        delete from Message where MemberID={0};
                                        delete from MemberContract where ParentID={0};
                                        delete from MemberChildren where ParentID={0};
                                        delete from ChangeChargeRecorde where VIPID={0};
                                        delete from MemberContact where MemberID={0};
                                        delete from MemberAssigned where MemberID={0};";
                        obj.ExecuteStoreCommand(string.Format(sql, id));
                    }
                    scope.Complete();
                }

                return true;
            }
            catch { return false; }
        }

        public MemberChildren GetChildrenByID(int id)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.MemberChildren.Where(c => c.ID == id).FirstOrDefault();
            }
        }
        public List<MemberChildren> GetAllByParent(int parentID)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.MemberChildren.Where(c => c.ParentID == parentID).ToList();
            }
        }
        public bool AddMemberChildren(MemberChildren model)
        {
            bool result = false;
            try
            {
                base.Add(model);
                result = RefrechChildren(model.ParentID);
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool UpdateMemberChildren(MemberChildren model)
        {
            bool result = false;
            try
            {
                base.Update(model);
                result = true;
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool DeleteMemberChildren(int id)
        {
            bool result = false;
            try
            {
                var model = this.GetChildrenByID(id);
                if (model != null)
                {
                    base.Delete<MemberChildren>(c => c.ID == id);
                    result = RefrechChildren(model.ParentID);
                }
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }

        public MemberContract GetContractByID(int id)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.MemberContract.Where(c => c.ID == id).FirstOrDefault();
            }
        }
        public List<MemberContract> GetContractsByParent(int parentID)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.MemberContract.Where(c => c.ParentID == parentID).ToList();
            }
        }
        public bool AddMemberContract(MemberContract model)
        {
            bool result = false;
            try
            {
                base.Add(model);
                result = RefrechContract(model.ParentID.Value);

            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool UpdateMemberContract(MemberContract model)
        {
            bool result = false;
            try
            {
                base.Update(model);
                result = RefrechContract(model.ParentID.Value);
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool DeleteMemberContract(int id)
        {
            bool result = false;
            try
            {

                var model = GetContractByID(id);
                if (model != null)
                {
                    base.Delete<MemberContract>(c => c.ID == id);
                    result = RefrechContract(model.ParentID.Value);
                }
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool DeleteMemberContractByParentID(int ParentID)
        {
            bool result = false;
            try
            {
                base.Delete<MemberContract>(c => c.ParentID == ParentID);
                result = true;
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }

        public vwMemberContact GetContactByID(int id)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.vwMemberContact.Where(c => c.ID == id).FirstOrDefault();
            }
        }
        public List<vwMemberContact> GetContactsByParent(UniversallySearchParam searchparma)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var query = obj.vwMemberContact.Where(c => c.MemberID == searchparma.IntObj1);
                if (searchparma.SubAssignedIn != null && searchparma.SubAssignedIn.Count > 0)
                {
                    //var AssignedIns = obj.MemberAssigned.Where(c => searchparma.SubAssignedIn.Contains(c.ManagerID)).Select(c => c.MemberID).ToList<int>();
                    query = query.Where(c => searchparma.SubAssignedIn.Contains(c.CreatorID));
                }
                return query.ToList();
            }
        }

        private MemberContact TransferToContact(vwMemberContact model)
        {
            var memberContact = new MemberContact()
            {
                ID = model.ID,
                CreateTime = model.CreateTime,
                Creator = model.Creator,
                CreatorID = model.CreatorID,
                Manager = model.Manager,
                MemberID = model.MemberID,
                Remark = model.Remark,
                Title = model.Title,
                Type = model.Type
            };
            return memberContact;
        }
        public bool AddMemberContact(vwMemberContact model)
        {
            bool result = false;
            try
            {
                base.Add(TransferToContact(model));
                result = true;
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool UpdateMemberContact(vwMemberContact model)
        {
            bool result = false;
            try
            {
                base.Update(TransferToContact(model));
                result = true;
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool DeleteMemberContact(int id)
        {
            bool result = false;
            try
            {
                base.Delete<MemberContact>(c => c.ID == id);
                result = true;
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }
        public bool DeleteMemberContactByParentID(int ParentID)
        {
            bool result = false;
            try
            {
                base.Delete<MemberContact>(c => c.MemberID == ParentID);
                result = true;
            }
            catch (Exception ex)
            { throw ex; }
            return result;
        }

        public bool TelExitsed(int id, string tel)
        {
            bool result = false;
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var query = obj.MemberInfo.Where(c => c.Tel == tel);
                if (id != 0)
                {
                    query = query.Where(c => c.ID != id);
                }
                result = query.Count() > 0;
            }
            return result;
        }

        bool RefrechContract(int memberid)
        {
            bool result = false;
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var Contracts = obj.MemberContract.Where(c => c.ParentID == memberid);
                int totalNum = Contracts.Count();
                decimal Total = Contracts.Sum(c => c.Amount);
                var memberinfo = obj.MemberInfo.FirstOrDefault(c => c.ID == memberid);
                if (memberinfo != null)
                {
                    memberinfo.ContractNum = totalNum;
                    memberinfo.ContractTotal = Total;
                    base.Update(memberinfo);
                    result = true;
                }
            }
            return result;
        }

        bool RefrechChildren(int memberid)
        {
            bool result = false;
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var Contracts = obj.MemberChildren.Where(c => c.ParentID == memberid);
                int totalNum = Contracts.Count();
                var memberinfo = obj.MemberInfo.FirstOrDefault(c => c.ID == memberid);
                if (memberinfo != null)
                {
                    memberinfo.IsChildren = totalNum > 0;
                    base.Update(memberinfo);
                    result = true;
                }
            }
            return result;
        }
    }
}
